import {
  Pressable,
  StyleSheet,
  View,
  Image,
  ScrollView,
  useWindowDimensions,
  Text,
  ImageBackground,
  Animated,
  NativeSyntheticEvent,
  NativeScrollEvent,
} from 'react-native'
import { flexCol } from '../assets/style/common'
import useGetStatusBar from '../utils/useGetStatusBar'
import { LinearGradient } from 'expo-linear-gradient'
import Price from '../component/price'
import {
  useCallback,
  useContext,
  useEffect,
  useMemo,
  useRef,
  useState,
} from 'react'
import Swiper from 'react-native-swiper'
import { BlurView } from 'expo-blur'
import { NavigationContext } from '@react-navigation/native'
import { delay } from '../utils'

export default function CommonGoods({ navigation }: any) {
  const [barHeight] = useGetStatusBar()
  const scrollRef = useRef<ScrollView>(null)
  const dimensions = useWindowDimensions()
  const height = dimensions.height - (barHeight + 88)
  const goods = useMemo(() => {
    const arr = [
      {
        id: 1,
        cover: [
          require('../assets/images/video1.jpg'),
          require('../assets/images/video2.jpg'),
        ],
        title: '小王子和月光下的玫瑰花园',
        address: '浙江 金华',
        price: '34',
      },
      {
        id: 2,
        cover: [
          require('../assets/images/video1_1.jpg'),
          require('../assets/images/video1_2.jpg'),
        ],
        title: '宫崎骏的小屋动漫风格',
        address: '浙江 金华',
        price: '32.8',
      },
      {
        id: 3,
        cover: [
          require('../assets/images/goodDetail.jpeg'),
          require('../assets/images/goodDetail2.jpeg'),
        ],
        title: '宫崎骏的夏天和花园的女孩',
        address: '浙江 金华',
        price: '40.8',
      },
    ]

    return arr.concat(arr.slice(0, 2))
  }, [])
  const [currentKey, setCurrentKey] = useState(0)
  function onBack() {
    navigation.goBack()
  }
  function onScrollEndDrag(e: NativeSyntheticEvent<NativeScrollEvent>) {
    let scrollY = e.nativeEvent.contentOffset.y
    let velocity = e.nativeEvent.velocity
    const current = currentKey * height
    const nextY = (currentKey + 1) * height
    const prevY = (currentKey === 0 ? 0 : currentKey - 1) * height

    const nextCount = () => {
      // 滚到下一个
      scrollRef.current?.scrollTo({ y: nextY, animated: true })
      setCurrentKey(currentKey + 1)
    }
    const prevCount = () => {
      // 滚到上一个
      scrollRef.current?.scrollTo({ y: prevY, animated: true })
      setCurrentKey(val => val - 1)
    }
    //速度
    if (velocity && velocity.y) {
      if (velocity.y > 1) {
        return nextCount()
      } else if (velocity.y < -1.5) {
        return prevCount()
      }
    }
    // 距离
    if (scrollY > current + height * 0.2) {
      nextCount()
    } else if (scrollY < current - height * 0.2) {
      prevCount()
    } else {
      scrollRef.current?.scrollTo({ y: current, animated: true })
    }
  }
  function goSearch() {
    navigation?.navigate('GoodSearchWrap', {
      screen: 'GoodSearch',
      params: {
        value: '',
      },
    })
  }
  const onMomentumScrollEnd = useCallback(
    delay(() => {
      if (currentKey === goods.length - 2) {
        setTimeout(() => {
          scrollRef.current?.scrollTo({ y: 0, animated: false })
          setCurrentKey(0)
        }, 300)
      }
    }),
    [currentKey, goods.length],
  )
  return (
    <View style={[styles.container, StyleSheet.absoluteFill]}>
      <View
        style={[
          styles.header,
          flexCol.default,
          {
            height: 40 + barHeight,
            paddingTop: barHeight,
          },
        ]}
      >
        <Pressable onPress={onBack} style={{ marginRight: 'auto' }}>
          <Text style={styles.menuSize}>&#xe601;</Text>
        </Pressable>
        <Pressable style={{ marginRight: 12 }} onPress={goSearch}>
          <Text style={styles.menuSize}>&#xe60a;</Text>
        </Pressable>
        <Pressable onPress={() => navigation.navigate('ShareModel')}>
          <Text style={styles.menuSize}>&#xe662;</Text>
        </Pressable>
      </View>
      <ScrollView
        ref={scrollRef}
        style={StyleSheet.absoluteFill}
        scrollEventThrottle={16}
        onScrollEndDrag={onScrollEndDrag}
        onMomentumScrollEnd={onMomentumScrollEnd}
        bounces={false}
      >
        {goods.map((item, key) => (
          <GoodCard {...item} key={key} currentKey={currentKey === key} />
        ))}
      </ScrollView>
    </View>
  )
}
interface GoodCardProp {
  id: number | string
  cover: any[]
  title: string
  address: string
  price: string
  currentKey: boolean
}
function GoodCard(props: GoodCardProp) {
  const paddingTop = useRef(new Animated.Value(0)).current
  const [barHeight] = useGetStatusBar()
  const dimensions = useWindowDimensions()
  const navigation = useContext(NavigationContext)
  const height = dimensions.height - (barHeight + 88)
  const [currentCoverIndex, setCurrentKey] = useState(0)
  function chooseParams() {
    navigation?.navigate('GoodParams')
  }
  function onIndexChanged(num: number) {
    setCurrentKey(num)
  }
  function goDetail() {
    navigation?.navigate('GoodDetail')
  }
  ;(useEffect(() => {
    Animated.timing(paddingTop, {
      toValue: props.currentKey ? barHeight + 40 : 0,
      duration: 300,
      useNativeDriver: false,
    }).start()
  }),
    [props.currentKey, props.id])
  const Covers = useMemo(() => {
    return (
      <Swiper
        key="bannerSwiper"
        showsVerticalScrollIndicator={false}
        autoplay={props.currentKey}
        autoplayTimeout={5}
        showsButtons={false}
        showsPagination={false}
        onIndexChanged={onIndexChanged}
        alwaysBounceVertical={false}
      >
        {props.cover.map((item: any, key) => (
          <Image
            key={key}
            style={{ width: '100%', height: '100%' }}
            source={item}
          />
        ))}
      </Swiper>
    )
  }, [props.currentKey, props.cover, props.id])
  return (
    <View style={[card.contain, { height }]}>
      <ImageBackground source={props.cover[0]} style={[card.swiperWrap]}>
        <BlurView
          intensity={40}
          tint="dark"
          style={StyleSheet.absoluteFillObject}
        >
          <View style={[flexCol.default, { flex: 1 }]}>
            <Animated.View
              style={{
                paddingTop: paddingTop,
                paddingBottom: 24,
              }}
            >
              {Covers}
            </Animated.View>
          </View>
          <View
            style={[card.countWrap, flexCol.default, { top: barHeight + 64 }]}
          >
            <Text style={card.count}>
              {currentCoverIndex + 1} / {props.cover.length}
            </Text>
          </View>
          <View style={card.descWrap}>
            <Price price={props.price} fontSize={28} fontWeight />
            <View style={[flexCol.default, card.titWrap]}>
              <Text style={card.tip}>精选</Text>
              <Text style={card.goodTit}>{props.title}</Text>
              <View style={card.sperate} />
              <Pressable style={flexCol.default} onPress={goDetail}>
                <Text style={card.goDetail}>详情</Text>
                <Text style={card.arrow}>&#xe643;</Text>
              </Pressable>
            </View>
            <Text style={card.otherInfo}>
              退货运费险 · 包邮 · {props.address}
            </Text>
          </View>
        </BlurView>
      </ImageBackground>
      <View style={flexCol(card.footer)}>
        <Image
          source={require('../assets/images/avatar.jpg')}
          style={card.storeIcon}
        />
        <View style={card.storeWrap}>
          <Text style={card.storeName}>猫头鹰画室</Text>
          <Text style={card.storeTip}>进店逛逛</Text>
        </View>
        <View style={[flexCol.default, { flexDirection: 'column' }]}>
          <Text style={card.cltIcon}>&#x10186;</Text>
          <Text style={card.cltTxt}>收藏</Text>
        </View>
        <LinearGradient
          colors={['#fbce6a', '#fed66f']}
          style={[flexCol(card.footBtn), card.leftBtn]}
          start={{ x: 0.2, y: 0.5 }}
          end={{ x: 0.8, y: 0.5 }}
        >
          <Pressable onPress={chooseParams} style={flexCol(card.footBtn)}>
            <Text style={card.gouwuIcon}>&#x10187;</Text>
          </Pressable>
        </LinearGradient>
        <LinearGradient
          colors={['#73d7f7', '#57aef0']}
          style={[flexCol(card.footBtn), card.rightBtn]}
          start={{ x: 0.2, y: 0.5 }}
          end={{ x: 0.8, y: 0.5 }}
        >
          <Pressable style={flexCol(card.footBtn)} onPress={chooseParams}>
            <Text style={card.footBtnTxt}>立即购买</Text>
          </Pressable>
        </LinearGradient>
      </View>
    </View>
  )
}
const card = StyleSheet.create({
  contain: {
    borderTopLeftRadius: 12,
    borderTopRightRadius: 12,
    overflow: 'hidden',
    paddingBottom: 12,
  },
  goodTit: {
    fontSize: 16,
    fontWeight: 'bold',
    color: '#333',
    flex: 1,
  },
  tip: {
    borderRadius: 4,
    backgroundColor: '#fed66f',
    overflow: 'hidden',
    fontSize: 14,
    color: '#fff',
    paddingHorizontal: 4,
    paddingVertical: 1,
    marginRight: 4,
  },
  sperate: {
    backgroundColor: '#ccc',
    width: 1,
    height: 14,
  },
  goDetail: {
    fontSize: 16,
    color: '#ff2222',
    fontWeight: 'bold',
    marginLeft: 12,
  },
  arrow: {
    fontFamily: 'iconfont',
    fontSize: 18,
    color: '#ff2222',
  },
  otherInfo: {
    fontSize: 12,
    marginTop: 8,
    color: '#999999',
  },
  descWrap: {
    borderRadius: 12,
    backgroundColor: '#fff',
    marginLeft: 12,
    marginRight: 12,
    marginBottom: 12,
    padding: 12,
  },
  titWrap: {
    marginTop: 4,
  },
  swiperWrap: {
    flexGrow: 1,
    backgroundColor: '#99999922',
    position: 'relative',
    resizeMode: 'cover',
  },
  swiper: {
    height: '80%',
  },
  countWrap: {
    position: 'absolute',
    right: 12,
    backgroundColor: '#333333',
    height: 24,
    width: 44,
    paddingHorizontal: 8,
    borderRadius: 12,
  },
  count: {
    fontSize: 14,
    color: '#fff',
  },
  leftBtn: {
    borderTopLeftRadius: 19,
    borderBottomLeftRadius: 19,
    textAlign: 'center',
    width: 60,
    marginLeft: 12,
  },
  rightBtn: {
    borderTopRightRadius: 19,
    borderBottomRightRadius: 19,
  },
  footBtn: {
    width: 100,
    height: 38,
    justifyContent: 'center',
  },
  gouwuIcon: {
    color: '#fff',
    marginLeft: 6,
    fontSize: 24,
    fontFamily: 'iconfont',
  },
  footBtnTxt: {
    textAlign: 'center',
    color: '#fff',
    fontSize: 14,
    fontWeight: 'bold',
  },
  cltIcon: {
    fontFamily: 'iconfont',
    fontSize: 20,
    color: '#fff',
  },
  cltTxt: {
    fontSize: 14,
    color: '#fff',
    textAlign: 'center',
  },
  footer: {
    width: '100%',
    height: 80,
    paddingHorizontal: 12,
  },
  storeIcon: {
    width: 44,
    height: 44,
    borderRadius: 20,
    marginRight: 10,
  },
  storeWrap: {
    height: 40,
    marginRight: 'auto',
  },
  storeName: {
    fontSize: 14,
    fontWeight: 'bold',
    color: '#ffffff',
    marginBottom: 4,
    marginTop: 2,
  },
  storeTip: {
    fontSize: 12,
    color: '#aaa',
  },
})
const styles = StyleSheet.create({
  container: {
    flexDirection: 'row',
    backgroundColor: '#333333',
    // width: '100%',
    // height: '100%'
  },
  header: {
    position: 'absolute',
    left: 0,
    width: '100%',
    top: 0,
    paddingHorizontal: 12,
    zIndex: 1,
  },
  menuSize: {
    fontSize: 24,
    color: '#fff',
    fontFamily: 'iconfont',
  },
  endStyle: {
    color: '#fff',
    textAlign: 'center',
  },
})
